// 初始化状态
import {loginJwtKey} from "../Axios/User.js";

function getStateJwtKey() {
    //获取jwt key
    const savedUser = JSON.parse(localStorage.getItem('userData'));
    if (!savedUser) {
        return ''
    }
    return savedUser.count.jwtKey;
}

//upDateStateJwtKey
async function upDateStateJwtKey() {
    const savedUser = await JSON.parse(localStorage.getItem('userData'));
    if (!savedUser) {
        window.location.replace('/login.html');
    }
    let userData = await loginJwtKey(savedUser.count.jwtKey).then(e => {
        let userData = e.data.data;

        saveState(savedUser.count.jwtKey, userData.name, userData.email, userData.introduction, userData.avatar); // 保存用户信息
        return {
            count: {
                jwtKey: savedUser.count.jwtKey,
                username: userData.name,
                email: userData.email,
                introduction: userData.introduction,
                image: userData.avatar
            }
        };
    })
    console.log(userData)
    return userData;
}

async function getState() {
    // userData 中初始化 状态
    // 从 localStorage 中获取 count 值
    await upDateStateJwtKey()

    const savedUser = await JSON.parse(localStorage.getItem('userData'));
    if (!savedUser || !savedUser.count) {
        return {
            count: null,
        }
    }
    return savedUser;
}

// 将状态保存到 localStorage
function saveState(jwtKey, username, email, introduction, image) {
    localStorage.setItem('userData', JSON.stringify({
        count: {
            jwtKey, username, email, introduction, image
        }
    }));
}

// 删除状态
function deleteState() {
    localStorage.removeItem('userData');
}


export {
    upDateStateJwtKey, getState, saveState, getStateJwtKey, deleteState
}